using System;
using System.Collections.Generic;
using System.Linq;

namespace SiteLib.Data
{
	public partial class SiteUser
	{
		public SiteUser()
		{
			AccessRoles = new List<AccessRole>();
		}

		private List<AccessRole> _accessRoles;
		public List<AccessRole> AccessRoles
		{
			get { return _accessRoles ?? (_accessRoles = new List<AccessRole>()); }
			set { _accessRoles = value; }
		}

		private void FillUserRoles()
		{
			List<SiteUserAccessRole> siteUserAccessRoles = SiteUserAccessRole.Search(null, UserId, null);
			foreach (var siteUserAccessRole in siteUserAccessRoles)
			{
				if (siteUserAccessRole.RoleId != null) AccessRoles.Add(AccessRole.Get(siteUserAccessRole.RoleId.Value));
			}
		}

		public static List<SiteUser> GetAllUsers()
		{
			return Search(null, null, null, null, null, null, null, null, null, null, null, null, false);
		}

		public SiteUser SearchById(int iUserId)
		{
			return Get(iUserId);
		}

		public static SiteUser SearchByEmail(string sEmail)
		{
			return
				Search(null, null, sEmail, null, null, null, null, null, null, null, null, null, false).FirstOrDefault();
		}

		public static SiteUser SearchByPasswordKey(string sPasswordKey)
		{
			return
				Search(null, null, null, null, null, null, null, null, null, null, null, null, false, null, null,
								sPasswordKey).FirstOrDefault();
		}

		public void UpdateInstance()
		{
			LastModifiedDate = DateTime.Now;

			Update();
		}

		public void MarkAsDeleted()
		{
			IsDeleted = true;

			Update();
		}

		public void Save()
		{
			CreatedDate = DateTime.Now;
			IsLockedOut = false;
			IsDeleted = false;
			LastLockedOutDate = DateTime.Now;
			LastLoginDate = DateTime.Now;
			NewEmailKey = Guid.NewGuid().ToString();
			NewPasswordKey = Guid.NewGuid().ToString();
		}
	}
}